package com.kun.oa.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kun.oa.mapper.RolePermissionMapper;
import com.kun.oa.vo.RespStat;
import com.kun.oa.entity.Account;
import com.kun.oa.mapper.AccountExample;
import com.kun.oa.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Classname AccountService
 * @Created by FangKun
 * @Date 2023/1/2 0002 下午 17:37
 */
@Service
public class AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    /**
     * 登录验证
     * @param loginName
     * @param password
     * @return
     */
    public Account validataAccount(String loginName, String password) {
        Account account = accountMapper.validataAccount(loginName,password);
        return account;
    }

    public PageInfo<Account> findByPage(int pageNum, int pageSize) {

        List<Account> list = accountMapper.selectByPermission();

        System.out.println(list.get(0));

        PageHelper.startPage(pageNum, pageSize);
        AccountExample example = new AccountExample();
        List<Account> accountList = accountMapper.selectByExample(example);
        return new PageInfo<>(accountList,5);
    }

    public RespStat deleteById(int id) {

        int row = accountMapper.deleteByPrimaryKey(id);

        if (row == 1) {
            return RespStat.build(200);
        } else {
            return RespStat.build(500, "删除失败");
        }
    }

    public boolean updateMsg(Account account) {
        return accountMapper.updateByPrimaryKeySelective(account)>0?true:false;
    }

    public Account selectById(int id) {
        return accountMapper.selectById(id);
    }

    public int modifyUserByAdmin(Integer id,String password) {
        return accountMapper.updatePasswordByAdmin(id,password);
    }

    /**
     * 用户注册
     * @return
     */
    @Transactional
    public boolean registerUser(Account account) {

        account.setRole("user");
        //默认昵称为登录名
        account.setNickName(account.getLoginName());

        int r1 = accountMapper.insertSelective(account);
        //TODO:暂时模拟角色id
        Integer roleId = 11;
        int r2 = rolePermissionMapper.insertAccountRoleRelation(account.getId(),roleId);

        return (r1 == 1 && r2 == 1) ? true : false;
    }
}
